import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout'
import { getToken } from '@/utils/auth'
import store from '@/store/index';

Vue.use(VueRouter)

export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/Login/Login.vue'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/404.vue'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [{
      path: 'home',
      component: () => import('@/views/Home.vue'),
      meta: { title: '首页', icon: 'el-icon-s-help' }
    }]
  }
]
//TODO 在开发时，直接操作asyncRouterMap数组添加，此时children若只有一个正常，两个以上children检测不到。js方面问题
export const asyncRouterMap = [
      {
        path: '/auth',
        component: Layout,
        redirect: '/auth/allot',
        children: [{
          path: 'allot',
          component: () => import('@/views/Auth/Auth.vue'),
          meta: { title: '分配权限', icon: 'el-icon-setting' }
        }]
      },
      {
        path: '/user',
        component: Layout,
        redirect:'/user/userlist',
        children:[{
            path: 'userlist',
            component: () => import('@/views/User/User.vue'),
            meta: { title: '人员管理',icon: 'el-icon-user'}
        }]
      },
      {
        path: '/stati',
        component:Layout,
        redirect: '/stati/statiTable',
        children: [{
            path: 'statiTable',
            component: () => import('@/views/Statistical/Statistical.vue'),
            meta: { title: '统计表', icon: 'el-icon-s-grid' }
        }]
      },
      {
        path: '/test',
        component: Layout,
        redirect: '/test/test1',
        meta: { title: 'TEST', icon: 'el-icon-s-help' },
        children: [
          {
            path: 'test1',
            component: () => import('@/views/test1'),
            meta: { title: 'TEST1', icon: 'el-icon-s-help'}
          },
          {
            path: 'test2',
            component: () => import('@/views/test2'),
            meta: { title: 'TEST2', icon: 'el-icon-s-help' }
          }
        ]
      },
      {
        path: '/qwe',
        component: Layout,
        meta: { title: 'QWE',icon: 'el-icon-s-help' },
        redirect: '/qwe/ewq',
        children:[
            {
                path: 'ewq',
                component: () => import('@/views/test1'),
                meta: { title: 'EWQ',icon: 'el-icon-s-help' },
            }
        ]
      },
      {
          path: '/tttt',
          component: Layout,
          meta: { title: 'SSSSS',icon: 'el-icon-s-help' },
          redirect: '/tttt/cesh/cesh1',
          children: [
              {
                  path: 'cesh',
                  meta: { title: 'CECSHI', icon : 'el-icon-s-help'},
                  redirect: '/tttt/cesh/cesh1',
                  component: () => import('@/views/Home'),
                  children: [
                    {
                        path: 'cesh1',
                        component: () => import('@/views/test1'),
                        meta: { title: 'CESH1', icon: 'el-icon-s-help' }
                    },
                    {
                        path: 'cesh2',
                        component: () => import('@/views/test1'),
                        meta: { title: 'CESH2', icon: 'el-icon-s-help' }
                    }
                  ]
              },
              {
                  path: 'cesh3',
                  component: () => import('@/views/test1'),
                  meta: { title: 'CECSH3', icon : 'el-icon-s-help'},
              }
          ]
      },
      {
        path: '/question',
        component: Layout,
        redirect: '/question/questionlist',
        meta: { title: '题目录入', icon: 'el-icon-document-copy' },
        children: [
          {
            path: 'questionlist',
            component: () => import('@/views/Question/Question'),
            meta: { title: '题目管理', icon: 'el-icon-document'},
          },
          {
            path: 'addmore',
            component: () => import('@/views/Question/Addmore'),
            meta: { title: '识别录入', icon: 'el-icon-document-add'},
          },
          {
            path: 'caseshow',
            component: () => import('@/views/Question/CaseShow'),
            meta: { title: '操作示例', icon: 'el-icon-takeaway-box' }
          }
        ]  
      },
      //其他到404页面
      {path: '*' , redirect: '/404' , hidden:true}
]
let arr = []
arr = asyncRouterMap
const createRouter = () => new VueRouter({
    //跳转时回到顶部
    scrollBehavior: () => ({y:0}),
    routes : constantRoutes
})
//此项目权限控制为： 将有权限的路由传给后端，从后端获取路由后，将path拿到并与asyncRouterMap比对，生成路由表
const router = createRouter()
const whiteList = ['/login']
router.beforeEach(async(to, from, next) => {
  console.log(arr)
    const hasToken = getToken()
    if(hasToken){
        if(to.path === '/login'){
            next({ path: '/'})
        } else {
            //检测有没有获取过权限
            const hasRole = store.getters.role
            if(hasRole!==''){
                //有则表示获取过 菜单也渲染过  放行
                next()
            } else {
                //用token获取用户信息
                try{
                    const getInfoRes = await store.dispatch('getInfo')
                    const Res = await store.dispatch('generateRoutes',getInfoRes.role)
                    console.log(Res,'generateRoutes')
                    Res.forEach(item => {
                        router.addRoute(item)
                    });
                    //添加重定向
                    router.addRoute({path: '*' , redirect: '/404' , hidden:true})
                    // router.getRoutes()
                    next({ ...to, replace: true})
                }catch(error){
                    console.log(error)
                }
            }
        }
    }else{
        //若没token  在白名单中不需要权限，否则到登录
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login')
        }
    }
})
//切换用户后，或者退出时清除动态加载的路由
export function resetRouter() {
    const nweRouter = createRouter()
    // 新路由实例matcer，映射赋值给旧路由实例的matcher
    router.matcher = nweRouter.matcher
}

export default router
